import { onMounted, ref } from "vue";
import { getCommonMessage } from "@/api/zixun";
import useChat from "./useChat";
import type { ChatItemProps } from "@/components/Chat/chat.vue";
import useHot from "./useHot";
import { interpreter } from "@/api/request";
import debounce from "@/utils/debounce";
import { AIToken, Token } from "@/utils/cache";

export default function useIndex() {
  const { hot, getHotList, changeHot } = useHot();
  const { source, chats, chating, getConversationHistory } = useChat();

  const ignoreChance = ref();
  const historyPopup = ref();
  const loginPopup = ref();

  const conversationChat = ref<{
    robot: ChatItemProps;
    user: ChatItemProps;
  } | null>(null);

  const hotMessage = ref<string>("");

  const onSendMessage = debounce(async (value: string) => {
    if (conversationChat.value) {
      uni.showToast({
        title: "正在回复中...",
        icon: "none"
      });
      return;
    }
    if (!Token.get() && !AIToken.get()) {
      loginPopup.value.show();
      return;
    }
    if (!value.trim()) {
      uni.showToast({
        title: "内容不能为空",
        icon: "none"
      });
      return;
    }
    hotMessage.value = "";
    conversationChat.value = {
      robot: { msg: "" },
      user: { question: value }
    };
    const [err] = await interpreter(getCommonMessage(value), {
      showLoading: false,
      ignores: []
    });
    if (err) {
      if (err.error_code === 403) {
        ignoreChance.value.open();
      } else {
        uni.showToast({
          duration: 3000,
          title: "发送失败，" + err.result.msg,
          icon: "none"
        });
      }
      conversationChat.value = null;
    }
  });

  const onSetHotMessage = (content: string) => {
    hotMessage.value = content;
  };

  onMounted(() => {
    getConversationHistory();
  });
  return {
    loginPopup,
    ignoreChance,
    historyPopup,
    source,
    chats,
    chating,
    conversationChat,
    hotMessage,
    hot,
    changeHot,
    getHotList,
    getConversationHistory,
    onSendMessage,
    onSetHotMessage
  };
}
